/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package easybooking.clients.gui;

import easybooking.data.Flight;
import easybooking.data.Plane;
import easybooking.data.Seat;
import easybooking.data.Type;
import java.awt.Component;
import java.awt.Container;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.rmi.RemoteException;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Vector;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.BorderFactory;
import javax.swing.ButtonGroup;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JRadioButton;
import javax.swing.JScrollPane;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;

/**
 *
 * @author tim
 * http://docs.oracle.com/javase/tutorial/uiswing/components/table.html#sorting
 * http://exampledepot.com/egs/javax.swing/radio_GetGroupCur.html
 */
public class BookingDialogSeatSelect extends JDialog {

    private EBInterface ebi;
    private JLabel lblSearch;
    private JTextField txfSearch;
    private JPanel buttonPanel;
    private JButton btnSelectSeat;
    private JPanel dialogPanel;
    private JButton btnCancel;
    private Icon blueIcon = new ImageIcon(EBInterface.class.getResource("../gui/images/boxBlue.png"));
    private Icon redIcon = new ImageIcon(EBInterface.class.getResource("../gui/images/boxRed.png"));
    private Icon greenIcon = new ImageIcon(EBInterface.class.getResource("../gui/images/boxGreen.png"));
    private ButtonGroup bg = new ButtonGroup();
    private HashMap hMap = new HashMap();
    private Flight f;

    public BookingDialogSeatSelect(EBInterface ebif) {
        ebi = ebif;
    }
         /**
     * gets and returns the selected seat from the table
     * @return the selected seat
     */
    public Seat getSelectedSeat() {
        return (Seat) hMap.get(this.getSelection(bg));
    }
/**
 * calls the generateComponents() method to create and show the BookingDialogSeatSelect
 * @param f is the flight object which should be edit
 */

    public void createAndShowDialog(Flight f) {
       this.f = null;
        this.f = f;
        generateComponents();
        this.setResizable(true);
        this.setTitle("Select Seat");
        this.setModal(true); // deaktivates input to other dialogs
        this.setLocationRelativeTo(null);
        this.pack();
        this.setVisible(true);
        this.toFront();

    }
/**
 * Generates all components to create and display the GUI
 */
    private void generateComponents() {

        try {
            // sets system default look and feel
            try {
                UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
            } catch (Exception exc) {
                System.err.println("Error loading L&F: " + exc);
            }
            dialogPanel = new JPanel();
            // Sets the border
            dialogPanel.setBorder(BorderFactory.createCompoundBorder(BorderFactory.createTitledBorder("Select Seat"), BorderFactory.createEmptyBorder(20, 20, 20, 20)));
            dialogPanel.setLayout(new GridBagLayout());
            GridBagLayout gbl = new GridBagLayout();



            Plane p = ebi.getInterfaceClient().findPlaneByKey(f.getPlaneId());
            Type t = ebi.getInterfaceClient().findTypeByKey(p.getTypeId());

//            System.out.println("Flight: " + f.getFlightId());
//            System.out.println("Plane: " + p.getPlaneId());
//            System.out.println("Type: " + t.getTypeId());


            Vector<Seat> bookedSeats = ebi.getInterfaceClient().findBookedSeatByFlight(f.getFlightId());
            Vector<Seat> allSeats = ebi.getInterfaceClient().findSeatByPlane(p.getPlaneId());
            Vector<Seat> boSeats = new Vector();


            Iterator si = allSeats.iterator();
            Iterator bsi = bookedSeats.iterator();


            // finds out the booked seats
            while (bsi.hasNext()) {
                Seat bs = (Seat) bsi.next();
                while (si.hasNext()) {
                    Seat s = (Seat) si.next();
//                    System.out.println(s.getSeatId() + "==" + bs.getSeatId());
                    if (s.getSeatId() == bs.getSeatId()) {
                        boSeats.add(s);
//                        System.out.println("Booked Seat: " + s.getSeatId());
                        break;
                    }
                }

            }


            // used to detect new line
            int j = 0;
            // Creates the RadioButtions and adds them to an assisated HashMap
            Iterator asi = allSeats.iterator();
            while (asi.hasNext()) {
                Seat s = (Seat) asi.next();
                JRadioButton rb = new JRadioButton();
                hMap.put(rb, s);
                rb.addChangeListener(cl);
                bg.add(rb);
                rb.setIcon(greenIcon);
                if (boSeats.contains(s)) {
                    rb.setIcon(redIcon);
                    rb.setEnabled(false);
                }
                // identifies the first line, used to write the characters
                if (s.getRow() == allSeats.firstElement().getRow()) {
                    addComponent(dialogPanel, gbl, new JLabel(String.valueOf(s.getSeat())), GridBagConstraints.NONE, GridBagConstraints.CENTER, this.charToInt(s.getSeat()) + 1, s.getRow(), 1, 1, 1, 0);
                }
                if (s.getRow() > j) {
                    addComponent(dialogPanel, gbl, new JLabel(String.valueOf(s.getRow())), GridBagConstraints.NONE, GridBagConstraints.CENTER, 0, s.getRow() + 1, 1, 1, 1, 0);
                    j++;
                }
                addComponent(dialogPanel, gbl, rb, GridBagConstraints.NONE, GridBagConstraints.CENTER, this.charToInt(s.getSeat()) + 1, s.getRow() + 1, 1, 1, 1, 0);

            }
            // adds the button panel
            addComponent(dialogPanel, gbl, this.createButtonPanel(), GridBagConstraints.NONE, GridBagConstraints.CENTER, 0, 0, 20, 1, 1, 0);
            // puts the dialog into a scroll pane
            JScrollPane sp = new JScrollPane(dialogPanel);
            // adds the scroll pane to the content pane
            this.getContentPane().add(sp);
        } catch (RemoteException ex) {
            Logger.getLogger(BookingDialogSeatSelect.class.getName()).log(Level.SEVERE, null, ex);
        }

    }

    // creates the putton Panel
            /**
 * Creates the buttons to select a seat or cancel
 * @return a JPanel with 2 buttons
 */
    private JPanel createButtonPanel() {

        buttonPanel = new JPanel();
        buttonPanel.setLayout(new GridBagLayout());
        GridBagLayout gbl = new GridBagLayout();

        btnSelectSeat = new JButton("Select Seat");
        btnSelectSeat.setActionCommand("BookingSelectSeat");
        btnSelectSeat.addActionListener(ebi);



        btnCancel = new JButton("Cancel");
        btnCancel.addActionListener(new ActionListener() {

            public void actionPerformed(ActionEvent e) {
                dispose();
            }
        });

        // Sets the buttons the same size
        btnCancel.setPreferredSize(btnSelectSeat.getPreferredSize());

        // Adds the buttons to the buttonPanel
        addComponent(buttonPanel, gbl, btnSelectSeat, GridBagConstraints.NONE, GridBagConstraints.WEST, 0, 0, 1, 1, 1, 0);
        addComponent(buttonPanel, gbl, btnCancel, GridBagConstraints.NONE, GridBagConstraints.EAST, 1, 0, 1, 1, 0, 0);

        return buttonPanel;
    }
    private ChangeListener cl = new ChangeListener() {

        public void stateChanged(ChangeEvent e) {
            JRadioButton rb = (JRadioButton) e.getSource();
            if (rb.isSelected() == true) {
                rb.setIcon(blueIcon);
            } else {
                rb.setIcon(greenIcon);
            }
        }
    };

    // This method converts a char in its ASCII int value
    private int charToInt(char c) {
        int i = c - 64;

        return i;
    }

    // This method returns the selected radio button in a button group
    private JRadioButton getSelection(ButtonGroup group) {
        for (Enumeration e = group.getElements(); e.hasMoreElements();) {
            JRadioButton b = (JRadioButton) e.nextElement();
            if (b.getModel() == group.getSelection()) {
                return b;
            }
        }
        return null;
    }
/**
 * defines the layout of the GUI
 * @param cont container to which the component is added
 * @param gbl GridBagLayout object
 * @param c compontent which is added to the container
 * @param fill how to use free space in the cell around the component
 * @param anchor where to fix an align the component
 * @param x x position in the grid layout
 * @param y y position in the grid layout
 * @param width number of columns the element should spread
 * @param hight number of rows the element should spread
 * @param weightx handels the horizontal free space
 * @param weighty handels the vertical free space
 */
    private static void addComponent(Container cont, GridBagLayout gbl, Component c, int fill, int anchor, int x, int y, int width, int hight, double weightx, double weighty) {
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.fill = fill;
        gbc.anchor = anchor;
        gbc.gridx = x;
        gbc.gridy = y;
        gbc.gridwidth = width;
        gbc.gridheight = hight;
        gbc.weightx = weightx;
        gbc.weighty = weighty;
        gbc.insets = new Insets(10, 10, 10, 10);
        //gbl.setConstraints(c, gbc);
        cont.add(c, gbc);


    }
}
